import axios from 'axios';
 
// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
});
 
// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    const local = useLocal()
    config.headers['Authorization'] = `Bearer ${local?.token}`;//每次请求实时获取token
    return config
  },
  error => {
    return error(error.response.status)
  }
);
 
// 响应拦截器
service.interceptors.response.use(
  response => {
    if(![200,401].includes(response?.data?.code)) {
      useMessage.warning(response?.data?.msg || '系统异常')
    }
    if([401].includes(response?.data?.code)){
      const local = useLocal()
      local.token = ''
      window.location.hash = 'login'
    }
    return {
      code:response?.data?.code || 400,
      msg:response?.data?.msg || '请求成功',
      data:response?.data?.data || ''
    } as any
  },
  error => {
    if (error && error.response) {
      if([401].includes(error.response.status)){
        const local = useLocal()
        local.token = ''
        window.location.hash = 'login'
      }
    }
    // useMessage.warning(error?.response?.data?.msg || '系统异常')
    return {
      code:400,
      msg:error.msg,
      data:{}
    }
    // 响应错误处理
  }
);
 
// 因为别的地方要用，所以就把实例暴露出去，导出
export const get = (url: string, params: any): Promise<any> => {
	return service.get(url, {
		params
	})
}

export const post = (url: string, params?: object, _object = {}): Promise<any> => {
  return service.post(url, params, _object)
}